<?php

if (!isset($_GET['file'])) {
    $dir = $_GET['dir'];
//show choices
    echo('<h2>Choose Backup File</h2>');
    $files = glob(BACKUP_DIR . $dir . '/*');
    if (!$files) {
        echo('<p>No backup configuration files found.</p>');
    } else {
        rsort($files);
        echo('<ul>');
        foreach ($files as $file) {
            $sfile = str_replace(BACKUP_DIR . $dir . '/', '', $file);
            echo('<li>' . $sfile
            . ' <span style="font-size:x-small">' . date('Y-m-d g:i:s a', filemtime($file)) . '</span>'
            . ' <a target="_blank" href="?action=view&amp;dir=' . $dir . '&amp;file=' . $sfile . '">'
            . 'View</a> <a href="?action=restore&amp;dir=' . $dir . '&amp;file=' . $sfile . '">Restore</a></li>');
        }
        echo('</ul>');
    }
} else {
//do restore (back up current)
    $dir = $_GET['dir'];
    $src = BACKUP_DIR . $dir . '/' . $_GET['file'];
    $dest = preg_replace('~-[0-9]{8}-[0-9]{6}$~', '', $_GET['file']);
    $backup = BACKUP_DIR . $dir . '/' . $dest . '-' . date('Ymd-His');
    if ($dir == 'config') {
        $dest = EZCONFIG;
    } else {
        $dest = EZCONFIG_TXT_DIR . $dest;
    }
    if (!file_exists($src)) {
        echo('<p>Specified file ' . $src . ' does not exist.</p>');
    } else if (!copy($dest, $backup)) {
        echo('<p>Failed to make backup of ' . $dest . '</p>');
    } else if (!unlink($dest)) {
        echo('<p>Failed to delete ' . $dest . ' (check permissions?). Removing backup.</p>');
        unlink($backup);
    } else if (!copy($src, $dest)) {
        echo('<p>Failed to restore backup (' . $src . ') to active (' . $dest . '). Restoring from backup (' . $backup . ')...</p>');
        if (!copy($backup, $dest)) {
            echo('<p>***FAILED TO RESTORE BACKUP***</p>');
        } else {
            echo('<p>Restored.</p>');
        }
    } else {
        echo('<p>Restored. Previous saved as ' . $backup);
    }
    $action = 'main';
}
